package com.jinhuhang.u2.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.AccountBean;
import com.jinhuhang.u2.myselfmodule.engine.invite.InviteActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.myselfmodule.engine.welfare.WelfareActivity;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.Result;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;
import com.mob.MobSDK;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import sun.misc.BASE64Encoder;


@SuppressLint("NewApi")
public class WebViewActivity extends SimpleBaseActivity {
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    private WebView webView;
    public static String url = "webAddress";
    public static String title = "title";
    public static String type = "type";
    String str;
    int  ty=0;
    @Override
    protected void initView() {
        super.initView();
        MobSDK.init(this, "1605f8d91ef52", "04cd9093419eeb30f43600a87f7e5acb");
        webView = ((WebView) findViewById(R.id.activityWebView));
        str = getIntent().getStringExtra("webAddress");
          ty = getIntent().getIntExtra(type,0);
        WebSettings localWebSettings = this.webView.getSettings();
        localWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        localWebSettings.setJavaScriptEnabled(true);
        localWebSettings.setDomStorageEnabled(false);
        localWebSettings.setDatabaseEnabled(false);
        localWebSettings.setAppCacheEnabled(false);
        localWebSettings.setAllowFileAccess(true);
        localWebSettings.setBuiltInZoomControls(false);
        localWebSettings.setSupportZoom(false);
        localWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        localWebSettings.setUseWideViewPort(true);
        localWebSettings.setLoadWithOverviewMode(true);
        webView.addJavascriptInterface(new JSInterface(), "activity");
        if (str != null) {
            this.webView.loadUrl(str);
        } else {
            zhangdanurl = zhangdanurl.replace("userId=0", "userId=" + MainActivity.uid);
            this.webView.loadUrl(zhangdanurl);
        }
        this.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ty==1 && MainActivity.userbean.getAssessment()==0){
                    MyDialog.tipDialog(WebViewActivity.this);
                }else {
                    finish();
                }
            }
        });
        String title = StringUtils.isEmpty(getIntent().getStringExtra("title")) ? "" : getIntent().getStringExtra("title");
        mTvTitle.setText(title);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_item_webview;
    }

    public static int showlogin = 0;
    public static String zhangdanurl = null;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (ty==1 &&MainActivity.userbean.getAssessment()==0) {
            MyDialog.tipDialog(WebViewActivity.this);
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                return true;

            }
        }
        return super.onKeyDown(keyCode, event);
    }

    class JSInterface {
        @JavascriptInterface
        public void jumpLogin() {
            zhangdanurl = str;
            showlogin = 1;
            Intent intent = new Intent(WebViewActivity.this, UserActivity.class);
            startActivity(intent);
            finish();
        }
        @JavascriptInterface
        public void setAssessment() {
            MyApplication.mSpUtil.putBoolean("assessment" + MainActivity.uid, true);
            MainActivity.userbean.setAssessment(1);
            MyApplication.mSpUtil.setUser(MainActivity.userbean);
            RetrofitUtils.getInstance().build()
                    .getAccountData(MainActivity.uid)
                    .compose(T.D())
                    .subscribe(new Result<HttpWrapper<AccountBean>>() {
                        @Override
                        protected void onSuccess(HttpWrapper<AccountBean> o) {
                            if (Constant.SUCCESS_CODE == o.code) {
                                MyApplication.mSpUtil.setAccount(o.data);
                            }
                        }
                    });
        }
        @JavascriptInterface
        public void jumpToInvert() {
            EventBus.getDefault().post(MainActivity.jumpInvert);
            Intent intent = new Intent(WebViewActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        @JavascriptInterface
        public void jumpShare() {
            Intent intent = new Intent(WebViewActivity.this, InviteActivity.class);
            startActivity(intent);
            finish();
        }

        @JavascriptInterface
        public void jumpwelfare() {
            Intent intent = new Intent(WebViewActivity.this, WelfareActivity.class);
            startActivity(intent);
            finish();
        }

        private BASE64Encoder base64Encoder = new BASE64Encoder();

        @JavascriptInterface
        public void shared1(String name, String str) {

            Platform.ShareParams sp = new Platform.ShareParams();
            sp.setTitleUrl(" ");
            sp.setShareType(Platform.SHARE_WEBPAGE);

            sp.setImageUrl("http://image.u2licai.com/jhh/sharesdkimg.jpg");// 网络图片rul
            sp.setTitle("我已瓜分5000万体验金红包！"); // 分享标题
            sp.setText("理财碰上双11，投资就是送送送！体检卡，京东卡，1111元消费基金停不下来！");
            String userName = MyApplication.mSpUtil.getUser().getUserName();
            String content = str + "?phone=" + base64Encoder.encode(userName.getBytes()) + "&userId=" + MyApplication.mSpUtil.getUser().getUserId();
            sp.setUrl(content); // 网友点进链接后，可以看到分享的详情
            sp.setSite("我已加入悠兔理财,一起来吧！");
            sp.setSiteUrl(content);
            if (name.equals(QQ.NAME)) {
                sp.setTitleUrl(content);
                sp.setSite("我已加入悠兔理财,一起来吧！");
                sp.setSiteUrl("");
            }
            Platform fb = ShareSDK.getPlatform(name);
// 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
            fb.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                    Log.i("1234", "onComplete");
                    if (platform.getName().equals(Wechat.NAME)) {
                        handler.sendEmptyMessage(2);
                    } else if (platform.getName().equals(WechatMoments.NAME)) {
                        handler.sendEmptyMessage(3);
                    } else if (platform.getName().equals(QQ.NAME)) {
                        handler.sendEmptyMessage(4);
                    }
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {
                    Log.i("1234", throwable.toString());
                    Message msg = new Message();
                    msg.what = 6;
                    msg.obj = throwable.getMessage();
                    handler.sendMessage(msg);
                }

                @Override
                public void onCancel(Platform platform, int i) {
                    Log.v("1234", "onCancel");
                    handler.sendEmptyMessage(5);
                }
            });
            fb.share(sp);
        }

        private Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        Toast.makeText(getApplicationContext(), "微博分享成功",
                                Toast.LENGTH_LONG).show();
                        break;

                    case 2:
                        Toast.makeText(getApplicationContext(), "微信分享成功",
                                Toast.LENGTH_LONG).show();
                        break;
                    case 3:
                        Toast.makeText(getApplicationContext(), "朋友圈分享成功",
                                Toast.LENGTH_LONG).show();
                        break;
                    case 4:
                        Toast.makeText(getApplicationContext(), "QQ分享成功",
                                Toast.LENGTH_LONG).show();
                        break;

                    case 5:
                        Toast.makeText(getApplicationContext(), "取消分享",
                                Toast.LENGTH_LONG).show();
                        break;
                    case 6:
                        Toast.makeText(getApplicationContext(), "分享失败!",
                                Toast.LENGTH_LONG).show();
                        break;
                    default:
                        break;
                }
            }

        };
    }
}